﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QLGT_2.Models;
using System.Data.Entity;
using System.Web.Security;

namespace QLGT_2.Controllers
{
    public class HomeController : Controller
    {
        QLGTContext db = new QLGTContext();

        public ActionResult Index()
        {
            ViewBag.tongsoGiaoTrinh = db.tbl_GiaoTrinhs.Count();
            ViewBag.tongsoTacGia = db.tbl_TacGias.Count();
            ViewBag.tongsoNXB = db.tbl_NhaXuatBans.Count();
            ViewBag.tongsoMonHoc = db.tbl_MonHocs.Count();

            #region ViewBag GT moi nhat
            string maGT="";
            var ma = from a in db.tbl_GiaoTrinhs select a.MaGiaoTrinh;
            foreach (var item in ma)
            {
                maGT = item.ToString();
            }

            var dsGiaoTrinh = from a in db.tbl_GiaoTrinhs
                              join b in db.tbl_GiaoTrinh_TacGias on a.MaGiaoTrinh equals b.MaGiaoTrinh
                              join c in db.tbl_TacGias on b.MaTacGia equals c.MaTacGia
                              join d in db.tbl_HocHams on c.MaHocHam equals d.MaHocHam
                              join e in db.tbl_HocVis on c.MaHocVi equals e.MaHocVi
                              where(a.MaGiaoTrinh == maGT)
                              select new kqtkGiaoTrinh
                              {
                                  MaGiaoTrinh = a.MaGiaoTrinh,
                                  TenGiaoTrinh = a.TenGiaoTrinh,
                                  MaTacGia = b.MaTacGia,
                                  TenTacGia = c.TenTacGia,
                                  MaHocHam = c.MaHocHam,
                                  HocHam = d.HocHam,
                                  VTHocHam = d.VietTat,
                                  MaHocVi = c.MaHocVi,
                                  HocVi = e.HocVi,
                                  VTHocVi = e.VietTat
                              };
            var dsGopMa = dsGiaoTrinh.GroupBy(m => m.MaGiaoTrinh).Select(m => m.FirstOrDefault()).ToList();
            List<kqtkGiaoTrinh> dsCuoi = new List<kqtkGiaoTrinh>();
            foreach (var a in dsGopMa)
            {
                string tacGia = "";
                foreach (var b in dsGiaoTrinh)
                {
                    if (b.MaGiaoTrinh.Trim() == a.MaGiaoTrinh.Trim())
                    {
                        if (b.HocHam != "Không có" && b.VTHocHam != null)
                        {
                            tacGia += b.VTHocHam.Trim() + ". TS. " + b.TenTacGia.Trim() + "; ";
                        }
                        else if (b.HocVi != "Không có" && b.VTHocVi != null)
                        {
                            tacGia += b.VTHocVi.Trim() + ". " + b.TenTacGia.Trim() + "; ";
                        }
                        else
                        {
                            tacGia += b.TenTacGia.Trim() + "; ";
                        }
                    }
                }
                if (tacGia != "")
                {
                    tacGia = tacGia.Substring(0, tacGia.Length - 2).Trim();
                }

                ViewBag.tenGiaoTrinh = a.TenGiaoTrinh;
                ViewBag.tacgia = tacGia;
            }
            #endregion

            #region ViewBag so GT theo He DT
            var soGT = from a in db.tbl_GiaoTrinhs
                       join b in db.tbl_GiaoTrinh_HeDTs on a.MaGiaoTrinh equals b.MaGiaoTrinh
                       join c in db.tbl_HeDaoTaos on b.MaHeDaoTao equals c.MaHeDaoTao
                       select new 
                        {
                            MaGiaoTrinh = a.MaGiaoTrinh,
                            TenGiaoTrinh = a.TenGiaoTrinh,
                            MaHeDaoTao = b.MaHeDaoTao,
                            TenHeDaoTao = c.TenHeDaoTao
                        };
            ViewBag.soDH = soGT.Where(m => m.TenHeDaoTao.ToString().Trim() == "Đại học").Count();
            ViewBag.soCD = soGT.Where(m => m.TenHeDaoTao.ToString().Trim() == "Cao đẳng").Count();
            ViewBag.soTC = soGT.Where(m => m.TenHeDaoTao.ToString().Trim() == "Trung cấp").Count();
            #endregion

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult Login()
        {
            HttpCookie ckMatKhau = Request.Cookies["MatKhau"];
            HttpCookie ckTenDangNhap = Request.Cookies["TenDangNhap"];
            if (ckTenDangNhap != null)
            {
                int id = CheckLogin(ckTenDangNhap.Value, ckMatKhau.Value, true);

                if (id == 1)
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        int CheckLogin(string TenDangNhap, string MatKhau, bool remember = false)
        {
            if (TenDangNhap != null && MatKhau != null)
            {
                string MatKhauMd5 = DuLieuChung.MaHoaMD5(MatKhau);

                var users = (from p in db.tbl_NguoiDungs
                             where p.TenDangNhap == TenDangNhap && p.MatKhau == MatKhauMd5
                             select p
                            );

                if (users.Count() == 0)
                {
                    ModelState.AddModelError("Error", "Tên đăng nhập hoặc mật khẩu không đúng.");
                    return 0;
                }

                //TbNguoiDung user = users.First();

                if (users.First().KhoaTaiKhoan == KhoaTaiKhoan.Khoa)
                {
                    ModelState.AddModelError("Error", "Tài khoản của bạn bị khóa.");
                    return 0;
                }

                if (remember)
                {
                    // check if cookie exists and if yes update
                    HttpCookie ckTenDangNhap = Request.Cookies["TenDangNhap"];


                    if (ckTenDangNhap != null)
                    {
                        //force to expire it
                        ckTenDangNhap.Values.Add("TenDangNhap", users.First().TenDangNhap);
                        ckTenDangNhap.Values.Add("MatKhau", MatKhau);
                        ckTenDangNhap.Expires = DateTime.Now.AddHours(-20);
                    }

                    HttpCookie ckMatKhau = null;

                    //create a cookie
                    ckTenDangNhap = new HttpCookie("TenDangNhap");
                    ckMatKhau = new HttpCookie("MatKhau");

                    ckTenDangNhap.Value = TenDangNhap;
                    ckMatKhau.Value = MatKhau;

                    ckTenDangNhap.Expires = DateTime.Today.AddDays(15);
                    ckMatKhau.Expires = DateTime.Today.AddDays(15);

                    Response.Cookies.Add(ckTenDangNhap);
                    Response.Cookies.Add(ckMatKhau);

                    //FormsAuthentication.SetAuthCookie(TenDangNhap, false);
                }

                Session["TenDangNhap"] = users.First().TenDangNhap;
                Session["ChucNang"] = db.tbl_ChucNang_Quyens.Where(m => m.MaQuyen == users.FirstOrDefault().MaQuyen).Select(m => m.tbl_ChucNang.MaCN).ToArray();
                Session["VietTat"] = db.tbl_ChucNang_Quyens.Where(m => m.MaQuyen == users.FirstOrDefault().MaQuyen).Select(m => m.tbl_ChucNang.VietTat).ToArray();
                return 1;
            }
            return 0;
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(string TenDangNhap, string MatKhau, bool remember = false)
        {
            if (ModelState.IsValid && TenDangNhap != null && MatKhau != null)
            {
                int id = CheckLogin(TenDangNhap, MatKhau, remember);

                if (id == 1)
                {
                    return RedirectToAction("Index", "Home");
                }
                return View();
            }
            return View();
        }

        public ActionResult Logout()
        {
            Session["TenDangNhap"] = null;
            Session["ChucNang"] = null;
            Session["VietTat"] = null;

            HttpCookie ckMatKhau = Request.Cookies["MatKhau"];
            HttpCookie ckTenDangNhap = Request.Cookies["TenDangNhap"];

            if (ckMatKhau != null)
            {
                ckMatKhau.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(ckMatKhau);
            }

            if (ckTenDangNhap != null)
            {
                ckTenDangNhap.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(ckTenDangNhap);
            }
            Session.Clear();
            Session.Abandon();
            Session.RemoveAll();

            return RedirectToAction("Login", "Home");
        }


    }
}
